/*
 * DCE400服务系统 -- 后端服务接口 -- 数据访问层 -- 业务员数据访问
 * 包括：业务员数据库增删改查
 *      业务员登录记录插入、查找
 */
package dao

import (
	"errors"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server_attence/app/entity"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/db"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/util"
	"time"
)

//********************************************
//Func  ：查询操作记录列表
//Method：GET
//Usage ：
//********************************************
func QueryOpRecordList(page, pageSize int, employId int64, startDate, endDate string) (int64, []*entity.OperatingRecord, error) {
	offset := (page - 1) * pageSize
	session := db.Session().Table("operating_record")
	defer session.Close()

	if employId > 0 { //根据mobile查找用户，如果用户是Admin授权，则可以查全部，否则只能输出自己
		session = session.And("employee_id = ?", employId)
	}

	if startDate != "" {
		dtLayout := "2006-01-02 15:04:05" //严格按照time包要求的格式
		loc := db.TZLocation()            //转换日期的时区
		_, serr := time.ParseInLocation(dtLayout, startDate, loc)
		if serr == nil {
			session = session.And("start_at >= ?", startDate)
		}
	}

	if endDate != "" {
		dtLayout := "2006-01-02 15:04:05" //严格按照time包要求的格式
		loc := db.TZLocation()            //转换日期的时区
		_, eerr := time.ParseInLocation(dtLayout, endDate, loc)
		if eerr == nil {
			session = session.And("end_at <= ?", endDate)
		}
	}

	if pageSize > 0 {
		session.Limit(pageSize, offset)
	}
	records := []*entity.OperatingRecord{}

	total, err := session.Omit("password").FindAndCount(&records)
	if err != nil {
		return 0, nil, err
	}
	return total, records, nil
}

//********************************************
//Func  ：查询操作记录详情
//Method：GET
//Param：operatorId操作员ID
//Usage ：
//********************************************
func QueryOpRecordDetail(recordId int64) (*entity.OperatingRecord, error) {
	session := db.Session().Table("operating_record")
	defer session.Close()
	if recordId > 0 {
		session = session.Where("id=?", recordId)
	} else {
		return nil, errors.New("unspecial record id")
	}

	var record entity.OperatingRecord
	has, err := session.Get(&record)
	if err != nil || has == false {
		return nil, err
	}
	return &record, nil
}

func InsertOpRecord(log entity.OperatingRecord) error {
	//登陆验证过了，需要搞一个token吗？
	log.Id = util.GenSnowflakeInt64()
	log.RecordAt = time.Now()
	session := db.Session().Table("operating_record")
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return err
	}
	_, err = session.Insert(&log) //插入
	if err != nil {
		return err
	}
	err = session.Commit()
	return err
}
